<?php
// 接口-工序报工接口
namespace interface\pda;

use control\auditClass;
use control\materialClass;
use control\equipmentClass;
use control\codeTemplateClass;
use control\optionSettingClass;
use control\machiningInOrderClass;

class processReportClass extends index
{
	private const table       = 'process_report';
	private const tableMx     = 'process_report_detail';
	private const tableStaff  = 'process_report_staff';
	private const page        = 'processReport';
	private const title       = '工序报工';
	private const stateOption = ['草稿', '待确认', '已确认'];
	
	public function search()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			'orderBy' => [
				'创建时间降序',
				'创建时间升序',
				'计划开始时间降序',
				'计划开始时间升序',
				'计划完工时间降序',
				'计划完工时间升序',
			],
			'search'  => [
				[
					'key'   => 'line',
					'name'  => '生产线',
					'array' => find([
						'table' => 'product_line',
						'field' => "id as value, name as text ",
						'where' => "coid = '" . self::$coid . "'",
					])['array'],
				],
				[
					'key'   => 'state',
					'name'  => '状态',
					'array' => self::stateOption,
				],
				[
					'key'   => 'teamType',
					'name'  => '班次',
					'array' => explode('，', para('teamType')),
				],
				[
					'key'   => 'teamId',
					'name'  => '班组',
					'array' => find([
						'table' => 'team',
						'field' => " id as value, name as text ",
						'where' => " state ='启用' and coid = '" . self::$coid . "' ",
					])['array'],
				],
				[
					'key'   => 'deviceId',
					'name'  => '关联设备',
					'array' => find([
						'table' => 'equipment',
						'field' => " id as value, name as text ",
						'where' => "coid = '" . self::$coid . "'",
					])['array'],
				],
			],
		];
	}
	
	public function getTeamStaff()
	{
		$teamId             = $this->post('teamId');
		$this->code         = 1;
		$this->resp['data'] = find([
			'table' => 'staff',
			'field' => " stid as value, name as text ",
			'where' => "stid in (select stid from team_detail where orderId = '$teamId' and coid = '" . self::$coid . "')",
		])['array'];
	}
	
	/**
	 * 列表
	 *
	 * @return void
	 */
	public function list(): void
	{
		$and   = "";
		$equal = [
			'coid'  => self::$coid,
			'state' => $this->post('state'),
		];
		//like查询数组
		$like = [
			"orderNo" => $this->post('orderNo'),//单据编号
		];
		//初始化
		$mwhere = search([
			'=' => [
				'type'   => $this->post('type'),
				'lineId' => $this->post('line'),
			],
		]);
		if ($mwhere) {
			$and .= " AND sendId In (SELECT id FROM machining_send_order WHERE 1=1 $mwhere )";
		}
		//如果没有查看所有员工请假记录的权限
		if (!$this->power(self::page, "seeAll")) {
			$and .= $this->seeSelf(self::page);
		}
		//获取查询结果
		$where        = search(["like" => $like, "=" => $equal]) . $and;
		$orderBy      = $this->post('orderBy') ?: '创建时间降序';
		$orderByArray = $this->orderBy([
			"search"  => $orderBy,
			"default" => "创建时间降序",
			"array"   => [
				"time"       => ["asc" => "创建时间升序", "desc" => "创建时间降序", "site" => 1],
				"recordDate" => ["asc" => "单据时间升序", "desc" => "单据时间降序", "site" => 2],
			],
		]);
		$page         = $this->page(["table" => self::table, "where" => $where, "order" => $orderByArray['orderBy']]);
		//数据分析
		$data['result'] = [];
		foreach ((array)$page['array'] as $array) {
			if ($array['sourceTable'] == 'machining_card_detail') {
				$machining_card_detail = query('machining_card_detail', "id = '$array[sendId]'");
				$sourceOrder           = query('machining_card', "id = '$machining_card_detail[orderId]'");
			} else {
				$sourceOrder = query('machining_send_order', "id = '$array[sendId]'");
			}
			$line             = query('product_line', "id = '$array[lineId]'");
			$process          = query('process', "id = '$array[processId]'");
			$team             = query('team', "id = '$array[teamId]'");
			$material         = query('material', "id = '$array[materialId]'");
			$materialSku      = query('material_sku', "id = '$array[materialSkuId]'");
			$data['result'][] = [
				"id"            => $array['id'],
				'orderNo'       => $array['orderNo'],
				'sourceOrderNo' => $sourceOrder['orderNo'],
				'workshop'      => $line['workshop'] . '-' . $line['name'],
				'processName'   => $process['name'],
				'teamNo'        => $array['teamNo'] . ' ' . $array['teamType'],
				'teamName'      => $team['name'],
				'materialCode'  => $material['code'],
				'brand'         => $material['brand'],
				'materialName'  => $material['name'],
				'model'         => $material['model'],
				'skuName'       => $materialSku['name'],
				'unit'          => $array['unit'],
				'yield'         => self::lostZero($array['yield'], 'numPrecision'),
				'goodNum'       => $array['yield'] - $array['badNum'],
				'badNum'        => self::lostZero($array['badNum'], 'numPrecision'),
				'staff'         => self::findStaff($array['stid']),
				'state'         => $array['state'],
				'time'          => $array['time'],
			];
		}
		$data['page'] = $page['para'];
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	
	/**
	 * 详情
	 *
	 * @return void
	 */
	public function detail(): void
	{
		$id   = $this->post('id');
		$info = query(self::table, "id = '" . $id . "'");
		if (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$audit = find([
				'table' => 'auditing_follow',
				'where' => " typeId = '$info[id]' order by time desc",
			]);
			if ($info['sourceTable'] == 'machining_card_detail') {
				$machining_card_detail = query('machining_card_detail', "id = '$info[sendId]'");
				$sourceOrder           = query('machining_card', "id = '$machining_card_detail[orderId]'");
				$machiningSendOrder    = query('machining_order', "id = '$sourceOrder[sourceId]'");
			} else {
				$sourceOrder        = query($info['sourceTable'], "id = '$info[sendId]'");
				$machiningSendOrder = $sourceOrder;
			}
			$line    = query('product_line', "id = '$info[lineId]'");
			$process = query('process', "id = '$info[processId]'");
			$team    = query('team', "id = '$info[teamId]'");
			// 缺陷
			$defectType    = find([
				'table' => self::tableMx,
				"where" => " orderId = '$info[id]' ",
				'field' => "any_value(problem) as problem, any_value(num) as num",
			])['array'];
			$teamStaff     = query('process_report_staff', "orderId = '$info[id]' order by list");
			$teamStaffName = $info['valuationType'] == '个人计件' ? '-' . self::findStaff($teamStaff['stid']) : '';
			
			$data['result'] = [
				'info'        => [
					"id"             => $info['id'],
					'orderNo'        => $info['orderNo'],
					'sourceOrderNo'  => $sourceOrder['orderNo'],
					'workshop'       => $line['workshop'] . '-' . $line['name'],
					'processName'    => $process['name'],
					'valuationType'  => $info['valuationType'],
					"device"         => equipmentClass::getName($info['deviceId']),
					"material"       => materialClass::getName($info['materialSkuId']),
					"sourceOrderNum" => self::lostZero($sourceOrder['num'], 'numPrecision') . $info['unit'],
					"startDate"      => $machiningSendOrder['startDate'],
					"endDate"        => $machiningSendOrder['endDate'],
					"text"           => $machiningSendOrder['text'],
					'staff'          => self::findStaff($info['stid']),
					'state'          => $info['state'],
					'time'           => $info['time'],
				],
				'reportWork'  => [
					'teamNo'     => $info['teamNo'] . '-' . $info['teamType'],
					'teamName'   => $team['name'] . $teamStaffName,
					'yield'      => self::lostZero($info['yield'], 'numPrecision') . ' ' . $info['unit'],
					'badNum'     => self::lostZero($info['badNum'], 'numPrecision') . $info['unit'],
					'startTime'  => $info['startTime'],
					'endTime'    => $info['endTime'],
					'text'       => $info['text'],
					'defectType' => $defectType,
				],
				'auditRecord' => $audit['array'],
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	public function getMaterial()
	{
		//获取记录
		if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
			$this->machiningCardSearch();
		} else {
			$and   = " and workFlow = 0 and isClose=0 and machiningOrderId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
			$like  = [
				'orderNo' => $this->post('orderNo'),
			];
			$equal = [
				'coid'     => self::$coid,
				'classify' => '生产派工',
				'state'    => '已确认',
			];
			if ($this->post('wd')) {
				$and .= " and materialId in (select id from material where 1=1  and ( `code` like '%" . $this->post('wd') . "%' OR `name` like '%" . $this->post('wd') . "%' OR `model` like '%" . $this->post('wd') . "%' )  )";
			}
			$where = search(["like" => $like, "=" => $equal]) . $and;
			$page  = $this->page([
				"table"   => "machining_send_order",
				"where"   => $where,
				'pageNum' => 50,
				"order"   => "orderNo desc",
			]);
			//获取表头
			$result = [];
			//获取记录
			foreach ($page['array'] as $array) {
				$material    = query('material', "id = '$array[materialId]'");
				$materialSku = query('material_sku', "id = '$array[materialSkuId]'");
				$line        = query('product_line', "id = '$array[lineId]'");
				$process     = query('process', "id = '$array[processId]'");
				$result[]    = [
					'mxId'         => $array['id'],
					'orderNo'      => $array['orderNo'],
					'orderDate'    => $array['recordDate'],
					'workshop'     => $line['workshop'] . '-' . $line['name'],
					'materialCode' => $material['code'],
					'materialName' => $material['name'],
					'model'        => $material['model'],
					'skuName'      => $materialSku['name'],
					'processName'  => $process['name'],
					'type'         => '生产派工单',
				];
			}
			$this->resp['data'] = [
				'result' => $result,
				'page'   => $page['para'],
			];
			$this->code         = 1;
		}
	}
	
	/**
	 * 生产流转卡
	 */
	public function machiningCardSearch()
	{
		$and   = " and a.sourceId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
		$equal = [
			'a.coid' => self::$coid,
		];
		$mAnd  = '';
		if ($this->post('wd')) {
			$mAnd .= " AND ( `c.code` like '%" . $this->post('wd') . "%' OR `c.name` like '%" . $this->post('wd') . "%' OR `c.model` like '%" . $this->post('wd') . "%' ) ";
		}
		if ($this->post('oid') && $this->post('source') == 'machining_card') {
			$mAnd .= " a.id = '{$this->post('oid')}' ";
		}
		$where = search(["=" => $equal]) . $mAnd . $and;
		$page  = $this->page([
			"table"   => " machining_card as a join machining_card_detail as b on a.id = b.orderId join material as c on c.id = a.materialId",
			'field'   => "a.*,b.processId,b.id as mxId,c.name,c.code,c.model",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "a.orderNo desc,b.list asc",
		]);
		//获取表头
		$result = [];
		//获取记录
		foreach ($page['array'] as $array) {
			$materialSku = query('material_sku', "id = '$array[materialSkuId]'");
			$line        = query('product_line', "id = '$array[lineId]'");
			$process     = query('process', "id = '$array[processId]'");
			$result[]    = [
				'mxId'         => $array['mxId'],
				'orderNo'      => $array['orderNo'],
				'orderDate'    => $array['recordDate'],
				'workshop'     => $line['workshop'] . '-' . $line['name'],
				'materialCode' => $array['code'],
				'materialName' => $array['name'],
				'model'        => $array['model'],
				'skuName'      => $materialSku['name'],
				'processName'  => $process['name'],
				'type'         => '生产流转卡',
			];
		}
		$this->resp['data'] = [
			'result' => $result,
			'page'   => $page['para'],
		];
		$this->code         = 1;
	}
	
	/**
	 * 编辑
	 */
	public function addMaterialEdit()
	{
		$id = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '你还没有编辑权限';
		} elseif (empty($id)) {
			$this->resp['warn'] = '请选择数据';
		} else {
			$data['preProcess'] = "";
			$data['device']     = '';
			if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
				$machining_card_detail = query('machining_card_detail', "id = '$id'");
				$sourceOrder           = query('machining_card', "id = '$machining_card_detail[orderId]'");
				$routingDetail         = query('routing_detail', "id = '$machining_card_detail[routingMxId]'");
				$process               = query('process', "id = '$machining_card_detail[processId]'");
				//取上一工序
				$preCardDetail = query('machining_card_detail', "orderId = '$machining_card_detail[orderId]' and list < $machining_card_detail[list] order by list desc");
				if (!empty($preCardDetail['id'])) {
					$preProcess         = query('process', "id = '$preCardDetail[processId]'");
					$reportNum          = find(array('table' => self::table, 'where' => "sendId = '$preCardDetail[id]'", 'sum' => "yield"));
					$reportNum          = self::lostZero($reportNum, 'numPrecision');
					$data['preProcess'] = "，上工序【{$preProcess['name']}】报工$reportNum " . $sourceOrder['unit'];
				}
				$data['reportNum'] = find(array('table' => self::table, 'where' => "sendId = '$machining_card_detail[id]'", 'sum' => "yield"));
			} else {
				$sourceOrder       = query('machining_send_order', "id = '$id'");
				$routingDetail     = query('routing_detail', "id = '$sourceOrder[routingMxId]'");
				$process           = query('process', "id = '$sourceOrder[processId]'");
				$data['reportNum'] = find(array('table' => self::table, 'where' => "sendId = '$sourceOrder[id]'", 'sum' => "yield"));
				$data['device']    = selectMultiple(array("name" => "deviceId", 'value' => $sourceOrder['deviceId'], "title" => "设备", 'where' => "coid = '" . self::$coid . "'", "table" => "equipment", 'sqlField' => 'name', 'sqlId' => 'id'));
			}
			$materialSku           = query('material_sku', "id = '$sourceOrder[materialSkuId]'");
			$material              = query('material', "id = '$sourceOrder[materialId]'");
			$line                  = query('product_line', "id = '$sourceOrder[lineId]'");
			$lineName              = $line['workshop'] . '-' . $line['name'];
			$data['process']       = $process['name'];
			$data['processId']     = $process['id'];
			$data['valuationType'] = $routingDetail['valuationType'];
			$data['planNum']       = self::lostZero($sourceOrder['num'], 'numPrecision');
			$data['unit']          = $sourceOrder['unit'];
			$data['materialName']  = $material['code'] . '-' . $material['name'] . '-' . $material['model'] . '-' . $materialSku['name'];
			$data['id']            = $id;
			$data['orderNo']       = $sourceOrder['orderNo'];
			$data['lineName']      = $lineName;
			$data['problem']       = $process['defectType'] ? explode('，', $process['defectType']) : [];
			
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	public function edit()
	{
		$id          = $this->post('id') ?: self::getId();
		$problemArr  = $this->post('problem') ? json_decode($this->post('problem'), true) : [];
		$numArr      = $this->post('num') ? json_decode($this->post('num'), true) : [];
		$mxIdArr     = $this->post('mxId') ? json_decode($this->post('mxId'), true) : [];
		$teamStaffId = $this->post('teamStaffId');
		//赋值
		$field      = array(
			"startTime" => $this->post('startTime'),
			"endTime"   => $this->post('endTime'),
			"sendId"    => $this->post('sendId'),//备注
			'teamNo'    => $this->post('teamNo'),
			"teamType"  => $this->post('teamType'),
			"teamId"    => $this->post('teamId'),
			"deviceId"  => $this->post('deviceId'),
			"yield"     => $this->post('yield') ? self::formattingFigure($this->post('yield'), 'numPrecision') : 0,
			"badNum"    => $this->post('badNum') ? self::formattingFigure($this->post('badNum'), 'numPrecision') : 0,
		);
		$annotation = [
			"sendId"   => '来源单据',
			'teamNo'   => '班次',
			"teamType" => '班次',
			"teamId"   => '班组',
			"yield"    => '产量',
		];
		$rules      = [
			"sendId"   => 'required',
			'teamNo'   => 'required',
			"teamType" => 'required',
			"teamId"   => 'required',
			"yield"    => 'required|numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			return;
		}
		
		$isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
		$warn          = '';
		if ($isProductCard) {
			$machining_card_detail     = query('machining_card_detail', "id = '$field[sendId]'");
			$field['sendId']           = $machining_card_detail['id'];
			$sourceOrder               = query('machining_card', "id = '$machining_card_detail[orderId]'");
			$field['routingMxId']      = $machining_card_detail['routingMxId'];
			$routingMx                 = query('routing_detail', "id = '$field[routingMxId]'");
			$field['processId']        = $machining_card_detail['processId'];
			$field['sourceTable']      = 'machining_card_detail';
			$field['machiningOrderId'] = $sourceOrder['sourceId'];
			$reportNum                 = find(['table' => self::table, 'where' => "sendId = '$machining_card_detail[id]' and id !='$id'", 'sum' => "yield"]);
			//获取上一节点工序
			$preProcessNode = query('routing_detail', "orderId = '$sourceOrder[routingId]' and mark = '是' and list < $routingMx[list] order by list desc");
			$preCardDetail  = query('machining_card_detail', "orderId = '$machining_card_detail[orderId]' and routingMxId = '$preProcessNode[id]'");
			$preReportNum   = find(['table' => self::table, 'where' => "sendId = '$preCardDetail[id]' and state = '已确认'", 'sum' => "yield"]);
			if (!empty($preProcessNode['id']) && self::formattingFigure($field['yield'] + $reportNum, 'numPrecision') > $preReportNum) {
				//判断是否已超出上一节点的报工数量
				$process = query('process', "id = '$preProcessNode[processId]'");
				$warn    = "报工总数量已超出了上一工序节点【{$process['name']}】的报工数量";
			}
		} else {
			$sourceOrder               = query('machining_send_order', "id = '$field[sendId]'");
			$field['sendId']           = $sourceOrder['id'];
			$field['routingMxId']      = $sourceOrder['routingMxId'];
			$field['processId']        = $sourceOrder['processId'];
			$field['sourceTable']      = 'machining_send_order';
			$field['machiningOrderId'] = $sourceOrder['machiningOrderId'];
			$reportNum                 = find(array('table' => self::table, 'where' => "sendId = '$sourceOrder[id]' and id !='$id'", 'sum' => "yield"));
		}
		if (self::formattingFigure($field['yield'] + $reportNum, 'numPrecision') > $sourceOrder['num']) {
			$warn = "此工序的报工总数量已超过计划数量";
		}
		
		$field['materialId']    = $sourceOrder['materialId'];
		$field['materialSkuId'] = $sourceOrder['materialSkuId'];
		$field['routingId']     = $sourceOrder['routingId'];
		$field['lineId']        = $sourceOrder['lineId'];
		$field['unit']          = $sourceOrder['unit'];
		
		$routing_detail         = query('routing_detail', "id = '$field[routingMxId]'");
		$field['valuationType'] = $routing_detail['valuationType'];
		$annotation             = [
			"processId"     => '工序',
			"materialSkuId" => '物料ID',
			"routingId"     => '工艺路线',
			"routingMxId"   => '工艺路线明细',
			"lineId"        => '生产线',
			"valuationType" => '计件方式',
			"unit"          => '单位',
		];
		$rules                  = [
			'processId'     => 'required',
			"materialSkuId" => 'required',
			"routingId"     => 'required',
			'routingMxId'   => 'required',
			"lineId"        => 'required',
			"valuationType" => 'required',
			"unit"          => 'required',
		];
		
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			return;
		}
		$info = query(self::table, " id = '" . $id . "' ");
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "权限不足";
		} elseif ($info['state'] == '已确认') {
			$this->resp['warn'] = '此报工已确认，不能编辑';
		} elseif (!empty($field['startTime']) && !empty($field['endTime']) && strtotime($field['endTime']) < strtotime($field['startTime'])) {
			$this->resp['warn'] = '结束时间不能小于开始时间';
		} elseif ($warn) {
			$this->resp['warn'] = $warn;
		} else {
			$this->startTrans();
			if (empty($info['id'])) {
				$userNo             = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'BG' . date('Ymd', strtotime($field['teamNo'])),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => " and coid = '" . self::$coid . "'",
				], $field);
				$field              = array_merge($field, array("id" => $id, 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
				$this->resp['warn'] = insert(array("table" => self::table, "field" => $field));
			} else {
				$this->resp['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
				$field['orderNo']   = $info['orderNo'];
			}
			$newIdArr = [];
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $mxId) {
					if (!empty($problemArr[$k])) {
						$newIdArr[] = $mxId;
						$mx         = query(self::tableMx, "id = '$mxId'");
						if (!empty($mx['id'])) {
							$warn = static::update(array(
								'table' => self::tableMx,
								'field' => array(
									'problem' => $problemArr[$k],
									'num'     => $numArr[$k],
								),
								'where' => "id = '$mx[id]'",
							));
						} else {
							$warn = static::insert(array(
								'table' => self::tableMx,
								'field' => array(
									'id'      => $mxId,
									'coid'    => self::$coid,
									'orderId' => $id,
									'problem' => $problemArr[$k],
									'num'     => $numArr[$k],
								),
							));
						}
						if (!in_array($warn, array("新增成功", "更新成功"))) {
							$this->resp['warn'] = $warn;
							break;
						}
					}
				}
			}
			if ($field['valuationType'] == '个人计件') {
				delete(array('table' => self::tableStaff, 'where' => "orderId = '$id'"));
				$warn = static::insert(array(
					'table' => self::tableStaff,
					'field' => array(
						'id'      => suiji(),
						'coid'    => self::$coid,
						'orderId' => $id,
						'stid'    => $teamStaffId,
					),
				));
				if (!in_array($warn, array("新增成功", "更新成功"))) {
					$this->resp['warn'] = $warn;
				}
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				delete([
					'table' => self::tableMx,
					'where' => " id not in ('" . implode("','", $newIdArr) . "') and orderId = '$id'",
				]);
				if ($this->resp['warn'] == '新增成功') {
					auditClass::operateRecord($id, '工序报工', '新建');
				}
				$process = query('process', "id = '$field[processId]'");
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . ",单号【{$field['orderNo']}】,工序【{$process['name']}】,ID：" . $id;
				$this->logText(array("type" => self::page, "text" => $text));
				//返回
				$this->resp['data'] = $id;
				$this->code         = 1;
			} else {
				$this->rollback();
			}
		}
		
		resp:
	}
	
	
	/**
	 * 提交
	 */
	public function commit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state' => '待确认',
		];
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此工序报工';
		} elseif ($info['state'] != '草稿') {
			$this->resp['warn'] = '此工序报工不是草稿状态，不能提交';
		} else {
			$bool = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($bool, ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '工序报工', '提交');
				//添加日志
				$type = mb_substr($bool, 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->resp['warn'] = '提交成功';
				$this->code         = 1;
			}
		}
	}
	
	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];
		
		if (!$this->power(self::page, 'confirm')) {
			$this->resp['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此' . self::title;
		} elseif ($info['state'] != '待确认') {
			$this->resp['warn'] = '此' . self::title . '不是待确认状态，不能确认';
		} else {
			$this->startTrans();
			$this->resp['warn'] = static::update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if ($info['valuationType'] == '班组计件') {
				$teamMx = find(array('table' => 'team_detail', "where" => "orderId = '$info[teamId]' order by list asc"));
				foreach ($teamMx['array'] as $array) {
					$warn = static::insert(array(
						'table' => self::tableStaff,
						'field' => [
							'id'      => self::getId(),
							'orderId' => $info['id'],
							'stid'    => $array['stid'],
							'coid'    => self::$coid,
						],
					));
					if ($warn != '新增成功') {
						$this->resp['warn'] = $warn;
						break;
					}
				}
			}
			$bool = (new \control\processReportClass())->qualityOrder($info['id']);
			if ($bool !== true) {
				$this->resp['warn'] = $bool;
			}
			
			/********增加工序库存表数据（以报工数量为准，先不管质检）**************/
			$bool = (new \control\processReportClass())->setInventory($info);
			if ($bool !== true) {
				$this->resp['warn'] = $bool;
			}
			/*********尾工序自动生成生产入库单************/
			$routingMx = query('routing_detail', "id = '$info[routingMxId]'");
			$routing   = query('routing', "id = '$routingMx[orderId]'");
			//尾工序
			$endRoutingDetail = query('routing_detail', "orderId = '$routing[id]' order by list desc");
			$state            = '';
			if ($routingMx['id'] == $endRoutingDetail['id'] && $routing['endProcessIn'] == '是') {
				$mainId = suiji();
				$userNo = codeTemplateClass::generateCode('machiningInOrder', [
					'prefix' => 'SCRK' . date('Ymd', strtotime($info['teamNo'])),
					'table'  => 'machining_in_order',
					'field'  => 'orderNo',
					'where'  => " and coid = '" . self::$coid . "'",
				], []);
				if ($info['sourceTable'] == 'machining_card_detail') {
					$machining_card_detail = query('machining_card_detail', "id = '$info[sendId]'");
					$sourceOrder           = query('machining_card', "id = '$machining_card_detail[orderId]'");
					$machiningOrderMxId    = $sourceOrder['sourceMxId'];
				} else {
					$sourceOrder        = query('machining_send_order', "id = '$info[sendId]'");
					$machiningOrderMxId = $sourceOrder['machiningOrderMxId'];
				}
				$machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
				
				$material = query('material', "id = '$info[materialId]'");
				$state    = $material['warehouse'] ? '已确认' : '草稿';
				$warn     = static::insert(array(
					'table' => 'machining_in_order',
					'field' => [
						'id'         => $mainId,
						'orderNo'    => $userNo,
						'state'      => $state,
						'coid'       => self::$coid,
						'stid'       => $this->control['stid'],
						'text'       => '尾工序自动生成',
						'lineId'     => $info['lineId'],
						'manager'    => $info['stid'],
						'recordDate' => $info['teamNo'],
					],
				));
				if ($warn !== '新增成功') {
					$this->resp['warn'] = $warn;
				}
				$warn = static::insert([
					"table" => 'machining_in_order_detail',
					"field" => [
						'id'            => suiji(),
						'orderId'       => $mainId,
						'coid'          => self::$coid,
						'sourceId'      => $machiningOrderMxId,
						'materialId'    => $info['materialId'],
						'materialSkuId' => $info['materialSkuId'],
						'num'           => $info['yield'],
						'unit'          => $sourceOrder['unit'],
						'warehouseId'   => $material['warehouse'],
						'batch'         => $machiningOrderMx['batch'],
					],
				]);
				if ($warn !== '新增成功') {
					$this->resp['warn'] = $warn;
				}
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				auditClass::operateRecord($info['id'], '工序报工', '确认');
				if ($routingMx['id'] == $endRoutingDetail['id'] && $routing['endProcessIn'] == '是' && $state == '已确认') {
					$mainId                = $mainId ?? '';
					$machiningInOrder      = query('machining_in_order', "id = '$mainId'");
					$machiningInOrderClass = new machiningInOrderClass();
					$machiningInOrderClass->insertInventory($machiningInOrder, false);
				}
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code         = 1;
				$this->resp['warn'] = '确认成功';
				$this->resp['data'] = $info['id'];
			} else {
				$this->rollback();
			}
		}
	}
	
	/**
	 * 删除
	 *
	 * @return void
	 */
	public function delete(): void
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					delete(["table" => self::tableMx, "where" => " orderId = '$id' "]);
					delete(["table" => 'auditing_follow', "where" => " typeId = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
}
